package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhander.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-09-25
 */
@RestController
@RequestMapping("/eduservice/video")
//@CrossOrigin
public class EduVideoController {

    @Autowired
    private VodClient vodClient;

    @Autowired
    private EduVideoService eduVideoService;

    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    @DeleteMapping("{id}")
    public R daleteVideo(@PathVariable String id){
        EduVideo video = eduVideoService.getById(id);
        String videoSourceId = video.getVideoSourceId();
        if (!StringUtils.isEmpty(videoSourceId)){

            R result = vodClient.removeAlyVideo(videoSourceId);
            if (result.getCode() == 20001){
                throw new GuliException(20001,"删除视频失败，熔断器。。。");
            }
        }

        eduVideoService.removeById(id);
        return R.ok();
    }

    @GetMapping("getvideoId/{videoid}")
    public R getvideoId(@PathVariable String videoid){
        EduVideo video = eduVideoService.getById(videoid);
        return R.ok().data("video",video);
    }

    @PostMapping("updateVideoById")
    public R updateVideoById(@RequestBody EduVideo video){
        boolean b = eduVideoService.updateById(video);
        return R.ok();
    }
    @DeleteMapping("updataVideoSourceIdAndOriginalName/{videoSourceId}")
    public R updataVideoSourceIdAndOriginalName(@PathVariable String videoSourceId){
        LambdaQueryWrapper<EduVideo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EduVideo::getVideoSourceId,videoSourceId);
        EduVideo video = eduVideoService.getOne(wrapper);
        if(video!=null){
            video.setVideoOriginalName(null);
            video.setVideoSourceId(null);
            eduVideoService.removeById(video.getId());
            eduVideoService.save(video);

        }
        return R.ok();
    }

}

